import React, { Component } from "react"
import PropTypes from "prop-types"
import { padMonthLeft, createRangeArr } from "../utility"

class MonthPicker extends Component {
  constructor(props) {
    super(props)
    const { year, month } = this.props
    this.state = {
      isOpen: false,
      selectYear: year,
      selectMonth: month
    }
  }

  componentDidMount() {
    // document.addEventListener("click", e => {
    //   this.setState({
    //     isOpen: false
    //   })
    // })
    document.addEventListener("click", this.handleDocumentClick)
  }

  componentWillUnmount() {
    // document.removeEventListener("click")
    document.removeEventListener("click", this.handleDocumentClick)
  }

  handleDocumentClick = e => {
    //如果所点击的元素对象是月份选择按钮组件中的元素，则直接返回，从而不关闭下拉框
    if (this.node.contains(e.target)) {
      return
    }
    this.setState({
      isOpen: false
    })
  }

  toggleDropdown = e => {
    e.preventDefault()
    // 在测试环境中 e.nativeEvent.stopImmediatePropagation 并不是存在，所以需要先判断是否存在
    // if (e.nativeEvent && e.nativeEvent.stopImmediatePropagation) {
    //   e.nativeEvent.stopImmediatePropagation()
    // }
    this.setState({ isOpen: !this.state.isOpen })
  }

  addActiveClass = (active, value) => {
    return active === value ? "dropdown-item active" : "dropdown-item"
  }

  handleSelectYear = (e, year) => {
    e.preventDefault()
    // if (e.nativeEvent && e.nativeEvent.stopImmediatePropagation) {
    //   e.nativeEvent.stopImmediatePropagation()
    // }
    this.setState({
      selectYear: year
    })
    this.props.onChangeDate(year, this.state.selectMonth)
  }

  handleSelectMonth = (e, month) => {
    e.preventDefault()
    // if (e.nativeEvent && e.nativeEvent.stopImmediatePropagation) {
    //   e.nativeEvent.stopImmediatePropagation()
    // }
    this.setState({
      isOpen: false,
      selectMonth: month
    })
    // 把当前所选择的年月传递出去
    this.props.onChangeDate(this.state.selectYear, month)
  }

  render() {
    const { isOpen, selectYear, selectMonth } = this.state
    const currentYear = new Date().getFullYear()

    const monthRange = createRangeArr(12, 1)
    const yearRange = createRangeArr(9, -4).map(number => currentYear + number)
    return (
      <div
        className="dropdown month-picker-component row justify-content-center align-items-center"
        ref={ref => (this.node = ref)}
      >
        <h4 className="col text-align-right">选择月份</h4>
        <div className="col text-align-left p-0">
          <button
            className="btn btn-lg btn-secondary dropdown-toggle"
            onClick={this.toggleDropdown}
          >
            {`${selectYear} 年 ${padMonthLeft(selectMonth)} 月`}
          </button>
          {isOpen && (
            <div className="dropdown-menu" style={{ display: "block" }}>
              <div className="row">
                <div className="col border-right year-ranges">
                  {yearRange.map((yearNumber, index) => (
                    <a
                      key={index}
                      className={this.addActiveClass(selectYear, yearNumber)}
                      href="#1"
                      onClick={e => this.handleSelectYear(e, yearNumber)}
                    >
                      {yearNumber + " 年"}
                    </a>
                  ))}
                </div>
                <div className="col month-ranges">
                  {monthRange.map((monthNumber, index) => (
                    <a
                      key={index}
                      className={this.addActiveClass(selectMonth, monthNumber)}
                      href="#1"
                      onClick={e => this.handleSelectMonth(e, monthNumber)}
                    >
                      {padMonthLeft(monthNumber) + " 月"}
                    </a>
                  ))}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    )
  }
}

MonthPicker.propTypes = {
  year: PropTypes.number.isRequired,
  month: PropTypes.number.isRequired,
  onChangeDate: PropTypes.func.isRequired
}

export default MonthPicker
